package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.account.client.RechargeInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.client.OrderInfoFeignClient;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.atguigu.tingshu.payment.util.PayUtil;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.model.Transaction;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;

	@Autowired
	private OrderInfoFeignClient orderInfoFeignClient;

	@Autowired
	private RechargeInfoFeignClient rechargeInfoFeignClient;

	@Autowired
	private WxPayV3Config wxPayV3Config;

	@Autowired
	private RSAAutoCertificateConfig config;

	@Autowired
	private UserInfoFeignClient userInfoFeignClient;

	@Override
	public Map<String, Object> createJsapi(String paymentType, String orderNo, Long userId) {
		//	声明一个变量存储支付金额：
		BigDecimal totalAmount = new BigDecimal("0.00");
		//保存支付交易记录
		if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)){
			//订单；--订单的金额从订单表中获取
			//通过订单编号获取订单信息
			Result<OrderInfo> orderInfoResult = orderInfoFeignClient.getOrderInfo(orderNo);
			Assert.notNull(orderInfoResult,"订单不存在");
			OrderInfo orderInfo = orderInfoResult.getData();
			Assert.notNull(orderInfo,"订单不存在");
			//细节判断
			if (!orderInfo.getOrderStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)){
				return new HashMap<>();
			}
			//总金额
			totalAmount = orderInfo.getOrderAmount();
		}else {
			//充值； -- 从充值记录中获取
			Result<RechargeInfo> rechargeInfoResult = rechargeInfoFeignClient.getRechargeInfo(orderNo);
			Assert.notNull(rechargeInfoResult,"充值记录不存在");
			RechargeInfo rechargeInfo = rechargeInfoResult.getData();
			Assert.notNull(rechargeInfo,"充值记录不存在");
			//细节判断
			if (!rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)){
				return new HashMap<>();
			}
			//总金额
			totalAmount = rechargeInfo.getRechargeAmount();
		}
		log.info("支付金额：{}",totalAmount);
		paymentInfoService.savePaymentInfo(paymentType,orderNo,userId,totalAmount);
		//对应生成的支付页面
		JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
		//跟之前下单示例一样，填充预下单参数
		PrepayRequest request = new PrepayRequest();
		Amount amount = new Amount();
		//单位是：分
		amount.setTotal(1);
		request.setAmount(amount);
		request.setAppid(wxPayV3Config.getAppid());
		request.setMchid(wxPayV3Config.getMerchantId());
		request.setDescription("测试商品标题");
		request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
		//在微信内部：订单商户号 out_trade_no 我们的平台叫：order_no;
		request.setOutTradeNo(orderNo);
		Payer payer = new Payer();
		Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
		Assert.notNull(userInfoVoResult,"查询用户信息失败");
		UserInfoVo userInfoVo = userInfoVoResult.getData();
		Assert.notNull(userInfoVo,"查询用户信息失败");
		payer.setOpenid(userInfoVo.getWxOpenId());
		request.setPayer(payer);
		//设置过期时间
		//response 包含了吊起支付所需的所有参数，可用于前端调用支付
		PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
		//声明map集合
		HashMap<String, Object> result = new HashMap<>();
		//赋值
		result.put("timeStamp", response.getTimeStamp()); // 时间戳
		result.put("nonceStr", response.getNonceStr());   // 随机字符串
		result.put("package", response.getPackageVal());  // 订单详情扩展字符串
		result.put("signType", response.getSignType());   // 签名方式
		result.put("paySign", response.getPaySign());     // 签名
		//返回数据
		return result;
	}

	@Override
	public Transaction queryPayStatus(String orderNo) {
		QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();
		queryRequest.setMchid(wxPayV3Config.getMerchantId());
		queryRequest.setOutTradeNo(orderNo);

		try {
			//构建service对象
			JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
			Transaction result = service.queryOrderByOutTradeNo(queryRequest);
			System.out.println(result.getTradeState());
			//返回数据
			return result;
		} catch (ServiceException e) {
			// API返回失败, 例如ORDER_NOT_EXISTS
			System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
			System.out.printf("reponse body=[%s]\n", e.getResponseBody());
		}
		//返回数据
		return null;
	}

	@Override
	public Transaction wxNotify(HttpServletRequest request) {
		// xxx?name=xx
		// request.getParameter("")
		//获取请求头数据
		String wechatPaySerial = request.getHeader("Wechatpay-Serial");
		String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
		String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
		String wechatSignature = request.getHeader("Wechatpay-Signature");
		//获取原始报文
		String requestBody = PayUtil.readData(request);
		//构造 RequestParam
		RequestParam requestParam = new RequestParam.Builder()
				.serialNumber(wechatPaySerial)
				.nonce(wechatpayNonce)
				.signature(wechatSignature)
				.timestamp(wechatTimestamp)
				.body(requestBody)
				.build();
		//防止消息重复发送
		//初始化 NotificationParser
		NotificationParser parser = new NotificationParser(config);
		try {
			Transaction transaction = parser.parse(requestParam, Transaction.class);
			//返回数据
			return transaction;
		} catch (Exception e) {
			//签名验证失败，返回401状态码
			log.error(e.getMessage(),e);
			throw new RuntimeException("验证失败");
		}
	}
}
